
package com.jf.cloud.auth.manager;

import cn.hutool.crypto.symmetric.AES;
import com.jf.cloud.common.response.ServerResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author 菠萝凤梨
 * @date 2022/1/19 16:02
 */
@Component
public class PasswordManager {
    private static final Logger logger = LoggerFactory.getLogger(PasswordManager.class);
    private static final long TEN_MINUTES = 1000 * 60 * 10;
    /**
     * 用于aes签名的key，16位
     */
    @Value("${auth.password.signKey}")
    public String passwordSignKey;

    public ServerResponseEntity<String> decryptPassword(String data) {
        AES aes = new AES(passwordSignKey.getBytes(StandardCharsets.UTF_8));
        String decryptStr;
        String decryptPassword;
        try {
            decryptStr = aes.decryptStr(data);
            long currentTimeMillis = System.currentTimeMillis();
            long timestamp = Long.parseLong(decryptStr.substring(0, 13));
            // 签名时间大于十分钟，提示请求超时
            if (timestamp + TEN_MINUTES < currentTimeMillis) {
                return ServerResponseEntity.showFailMsg("请求超时");
            }
            decryptPassword = decryptStr.substring(13);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ServerResponseEntity.showFailMsg("AES解密错误");
        }
        return ServerResponseEntity.success(decryptPassword);
    }
}
